package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"path/filepath"

	"jianianhua-server/config"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func main() {
	fmt.Println("开始初始化数据库...")

	// 加载配置
	cfg := config.LoadConfig()
	fmt.Printf("数据库配置: %s:%s/%s\n", cfg.DBHost, cfg.DBPort, cfg.DBName)

	// 连接数据库
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		cfg.DBUsername, cfg.DBPassword, cfg.DBHost, cfg.DBPort, cfg.DBName)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("数据库连接失败:", err)
	}
	fmt.Println("数据库连接成功")

	// 读取SQL文件
	sqlFile := filepath.Join("..", "..", "scripts", "init_database_complete.sql")
	sqlContent, err := ioutil.ReadFile(sqlFile)
	if err != nil {
		log.Fatal("读取SQL文件失败:", err)
	}

	// 执行SQL脚本
	sql := string(sqlContent)
	result := db.Exec(sql)
	if result.Error != nil {
		log.Printf("执行SQL脚本警告: %v", result.Error)
	} else {
		fmt.Println("SQL脚本执行成功")
	}

	// 验证表结构
	tables := []string{"users", "categories", "products", "orders", "appointment_configs", "appointments", "banners"}
	for _, table := range tables {
		var count int64
		db.Raw(fmt.Sprintf("SELECT COUNT(*) FROM %s", table)).Scan(&count)
		fmt.Printf("表 %s: %d 条记录\n", table, count)
	}

	fmt.Println("数据库初始化完成！")
}
